<!-- ❗Errors in the form are set on line 60 -->
<script setup>
import { loginByUsername } from '@/api/system/index'
import { useGenerateImageVariant } from '@core/composable/useGenerateImageVariant'
import authV2LoginIllustrationBorderedLight from '@images/pages/auth-v2-login-illustration-bordered-light.png'
import authV2LoginIllustrationDark from '@images/pages/auth-v2-login-illustration-dark.png'
import authV2LoginIllustrationLight from '@images/pages/auth-v2-login-illustration-light.png'
import authV2MaskDark from '@images/pages/misc-mask-dark.png'
import authV2MaskLight from '@images/pages/misc-mask-light.png'
import { VNodeRenderer } from '@layouts/components/VNodeRenderer'
import { themeConfig } from '@themeConfig'
import { VForm } from 'vuetify/components/VForm'

const authThemeImg = useGenerateImageVariant(authV2LoginIllustrationLight, authV2LoginIllustrationDark, authV2LoginIllustrationBorderedLight, true)
const authThemeMask = useGenerateImageVariant(authV2MaskLight, authV2MaskDark)

definePage({
  meta: {
    layout: 'blank',
    unauthenticatedOnly: true,
  },
})

const isPasswordVisible = ref(false)
const route = useRoute()
const router = useRouter()
const ability = useAbility()

const errors = ref({
  username: undefined,
  password: undefined,
})

const refVForm = ref()

// const credentials = ref({
//   email: 'admin@demo.com',
//   password: 'admin',
// })
// options: [
//     {value: '000000',label: '管理平台'},
//     {value: '537209',label: '江苏杰士德精密工业有限公司'}
// ]
const loginForm = ref({
  tenantId: '537209', // 租户ID
  username: '', // 用户名
  password: '', // 密码
  type: "account", // 账号类型
})
const rememberMe = ref(false)

/*const login = async () => {
  try {
    const res = await $api('/auth/login', {
      method: 'POST',
      body: {
        email: credentials.value.email,
        password: credentials.value.password,
      },
      onResponseError({ response }) {
        console.log(response, 'response');
        errors.value = response._data.errors
      },
    })

    const { accessToken, userData, userAbilityRules } = res

    useLocalStorage('userAbilityRules').value = userAbilityRules
    useCookie('userAbilityRules').value = userAbilityRules
    useLocalStorage('userData').value = userData
    useCookie('userData').value = userData
    useCookie('accessToken').value = accessToken
      router.replace(route.query.to ? String(route.query.to) : '/')
    })
  } catch (err) {
    console.error(err)
  }
}*/
const login = async () => {
  try {
    let params = {
      tenantId: loginForm.value.tenantId, // 租户ID
      username: loginForm.value.username, // 用户名
      password: loginForm.value.password, // 密码
      type: loginForm.value.type, // 账号类型
    }
    const res = await loginByUsername(params)
    console.log('登录成功:', res)
    // 保存 token 或跳转
  } catch (err) {
    console.error('登录失败:', err.message || err)
  } finally { // 不管有没有错误，都会执行
    console.error('登录失败:', err.message || err)
  }
}
const onSubmit = () => {
  getCode();
  refVForm.value?.validate().then(({ valid: isValid }) => {
    if (isValid)
      login()
  })
}
</script>

<template>
  <RouterLink to="/">
    <div class="auth-logo d-flex align-center gap-x-3">
      <VNodeRenderer :nodes="themeConfig.app.logo" />
      <h1 class="auth-title">
        {{ themeConfig.app.title }}
      </h1>
    </div>
  </RouterLink>

  <VRow no-gutters class="auth-wrapper bg-surface">
    <VCol md="8" class="d-none d-md-flex">
      <div class="position-relative bg-background w-100 me-0">
        <div class="d-flex align-center justify-center w-100 h-100" style="padding-inline: 6.25rem;">
          <VImg max-width="613" :src="authThemeImg" class="auth-illustration mt-16 mb-2" />
        </div>

        <img class="auth-footer-mask" :src="authThemeMask" alt="auth-footer-mask" height="280" width="100">
      </div>
    </VCol>

    <VCol cols="12" md="4" class="auth-card-v2 d-flex align-center justify-center">
      <VCard flat :max-width="500" class="mt-12 mt-sm-0 pa-4">
        <VCardText>
          <h4 class="text-h4 mb-1">
            欢迎来到 <span class="text-capitalize"> {{ themeConfig.app.title }} </span>! 👋🏻
          </h4>
          <p class="mb-0"> 请登录到您的帐户并开始使用</p>
        </VCardText>
        <!-- <VCardText>
          <VAlert color="primary" variant="tonal">
            <p class="text-sm mb-2">
              Admin Email: <strong>admin@demo.com</strong> / Pass: <strong>admin</strong>
            </p>
            <p class="text-sm mb-0">
              Client Email: <strong>client@demo.com</strong> / Pass: <strong>client</strong>
            </p>
          </VAlert>
        </VCardText> -->
        <VCardText>
          <VForm ref="refVForm" @submit.prevent="onSubmit">
            <VRow style="width: 350px">
              <!-- 账号 -->
              <VCol cols="12">
                <AppTextField v-model="loginForm.username" label="账号" placeholder="JST0000" type="text" autofocus
                  :rules="[requiredValidator]" :error-messages="errors.username" />
              </VCol>

              <!-- 密码 -->
              <VCol cols="12">
                <AppTextField v-model="loginForm.password" label="密码" placeholder="············"
                  :rules="[requiredValidator]" :type="isPasswordVisible ? 'text' : 'password'" autocomplete="password"
                  :error-messages="errors.password"
                  :append-inner-icon="isPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'"
                  @click:append-inner="isPasswordVisible = !isPasswordVisible" />

                <!-- <div class="d-flex align-center flex-wrap justify-space-between my-6">
                  <VCheckbox v-model="rememberMe" label="记住我" />
                  <RouterLink class="text-primary ms-2 mb-1" :to="{ name: 'forgot-password' }">忘记密码?</RouterLink>
                </div> -->
                <VBtn class="my-6" block type="submit">登录</VBtn>
              </VCol>
              <!-- 注册账户 -->
              <!-- <VCol cols="12" class="text-center">
                <span>还没有账户?</span>
                <RouterLink class="text-primary ms-1" :to="{ name: 'register' }">创建账户</RouterLink>
              </VCol> -->
            </VRow>
          </VForm>
        </VCardText>
      </VCard>
    </VCol>
  </VRow>
</template>

<style lang="scss">
@use "@core/scss/template/pages/page-auth";
</style>
